<template>
  <el-dialog
    v-model="dialogVisible"
    title="赛程日历"
    width="90%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="calendar-container">
      <!-- 日历头部控制 -->
      <div class="calendar-header">
        <div class="header-left">
          <el-button @click="previousMonth" :icon="ArrowLeft">上月</el-button>
          <span class="current-month">{{ currentYear }}年{{ currentMonth }}月</span>
          <el-button @click="nextMonth">下月<el-icon class="el-icon--right"><ArrowRight /></el-icon></el-button>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="goToToday">今天</el-button>
          <el-button @click="refreshCalendar">刷新</el-button>
        </div>
      </div>

      <!-- 星期标题 -->
      <div class="weekdays">
        <div v-for="day in weekdays" :key="day" class="weekday">
          {{ day }}
        </div>
      </div>

      <!-- 日历网格 -->
      <div class="calendar-grid">
        <div
          v-for="(date, index) in calendarDates"
          :key="index"
          :class="[
            'calendar-day',
            { 'other-month': date.otherMonth },
            { 'today': isToday(date.date) },
            { 'has-events': date.events.length > 0 }
          ]"
          @click="handleDateClick(date)"
        >
          <div class="day-header">
            <span class="day-number">{{ date.date.getDate() }}</span>
            <span v-if="isToday(date.date)" class="today-label">今天</span>
          </div>

          <!-- 赛程事件列表 -->
          <div class="events-container">
            <div
              v-for="event in date.events.slice(0, maxEventsPerDay)"
              :key="event.id"
              :class="['event-item', `event-${getStatusClass(event.status)}`]"
              @click.stop="handleEventClick(event)"
            >
              <div class="event-time">
                {{ formatEventTime(event.startTime) }}
              </div>
              <div class="event-title">
                {{ event.project?.name || '未命名赛事' }}
              </div>
              <div class="event-venue">
                {{ event.venue?.name || '' }}
              </div>
            </div>

            <!-- 更多事件提示 -->
            <div
              v-if="date.events.length > maxEventsPerDay"
              class="more-events"
              @click.stop="handleShowMoreEvents(date)"
            >
              +{{ date.events.length - maxEventsPerDay }} 更多
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 赛程详情对话框 -->
    <el-dialog
      v-model="eventDetailVisible"
      title="赛程详情"
      width="600px"
      append-to-body
    >
      <div v-if="selectedEvent" class="event-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">{{ selectedEvent.project?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(selectedEvent.status)">
              {{ getStatusText(selectedEvent.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="场地名称">{{ selectedEvent.venue?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="场地位置">{{ selectedEvent.venue?.location || '-' }}</el-descriptions-item>
          <el-descriptions-item label="轮次">{{ selectedEvent.round }}</el-descriptions-item>
          <el-descriptions-item label="主裁判">{{ selectedEvent.referee?.realName || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDateTime(selectedEvent.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDateTime(selectedEvent.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="比赛时长" :span="2">
            {{ getDuration(selectedEvent.startTime, selectedEvent.endTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 更多事件对话框 -->
    <el-dialog
      v-model="moreEventsVisible"
      title="当日赛程"
      width="700px"
      append-to-body
    >
      <div v-if="selectedDateEvents.length > 0" class="events-list">
        <div
          v-for="event in selectedDateEvents"
          :key="event.id"
          :class="['event-card', `event-${getStatusClass(event.status)}`]"
          @click="handleEventClick(event)"
        >
          <div class="event-card-time">
            {{ formatEventTime(event.startTime) }} - {{ formatEventTime(event.endTime) }}
          </div>
          <div class="event-card-title">{{ event.project?.name || '未命名赛事' }}</div>
          <div class="event-card-venue">{{ event.venue?.name || '' }}</div>
          <div class="event-card-status">
            <el-tag :type="getStatusTagType(event.status)" size="small">
              {{ getStatusText(event.status) }}
            </el-tag>
          </div>
        </div>
      </div>
      <div v-else class="no-events">
        当日无赛程安排
      </div>
    </el-dialog>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import {
  getSchedulesByDateRange,
  getScheduleById
} from '@/api/schedule'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'schedule-updated'])

// 响应式数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth() + 1)
const calendarEvents = ref([])
const eventDetailVisible = ref(false)
const moreEventsVisible = ref(false)
const selectedEvent = ref(null)
const selectedDateEvents = ref([])

// 配置
const maxEventsPerDay = 3
const weekdays = ['日', '一', '二', '三', '四', '五', '六']

// 计算属性
const calendarDates = computed(() => {
  const dates = []
  const firstDay = new Date(currentYear.value, currentMonth.value - 1, 1)
  const startDate = new Date(firstDay)
  startDate.setDate(startDate.getDate() - firstDay.getDay())

  for (let i = 0; i < 42; i++) {
    const currentDate = new Date(startDate)
    currentDate.setDate(startDate.getDate() + i)

    const dateStr = formatDateForQuery(currentDate)
    const events = calendarEvents.value.filter(event => {
      const eventDate = formatDateForQuery(new Date(event.startTime))
      return eventDate === dateStr
    })

    dates.push({
      date: currentDate,
      otherMonth: currentDate.getMonth() !== currentMonth.value - 1,
      events: events.sort((a, b) => new Date(a.startTime) - new Date(b.startTime))
    })
  }

  return dates
})

// 工具方法
const formatDateForQuery = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatEventTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getDuration = (startTime, endTime) => {
  if (!startTime || !endTime) return '-'
  const start = new Date(startTime)
  const end = new Date(endTime)
  const diff = end - start
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  return `${hours}小时${minutes}分钟`
}

const isToday = (date) => {
  const today = new Date()
  return date.getDate() === today.getDate() &&
         date.getMonth() === today.getMonth() &&
         date.getFullYear() === today.getFullYear()
}

const getStatusClass = (status) => {
  const statusMap = {
    '未开始': 'pending',
    '进行中': 'progress',
    '已结束': 'completed',
    '延期': 'postponed',
    '取消': 'cancelled'
  }
  return statusMap[status] || 'pending'
}

const getStatusTagType = (status) => {
  const statusMap = {
    '未开始': 'info',
    '进行中': 'warning',
    '已结束': 'success',
    '延期': 'warning',
    '取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    '未开始': '未开始',
    '进行中': '进行中',
    '已结束': '已结束',
    '延期': '延期',
    '取消': '取消'
  }
  return statusMap[status] || status
}

// API调用方法
const fetchCalendarEvents = async () => {
  try {
    const startDate = new Date(currentYear.value, currentMonth.value - 1, 1)
    const endDate = new Date(currentYear.value, currentMonth.value, 0)

    // 扩展查询范围，包含前后几天的数据
    startDate.setDate(startDate.getDate() - 7)
    endDate.setDate(endDate.getDate() + 7)

    const response = await getSchedulesByDateRange(
      startDate.toISOString().split('T')[0] + ' 00:00:00',
      endDate.toISOString().split('T')[0] + ' 23:59:59'
    )

    if (response.code === 200) {
      calendarEvents.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取赛程数据失败')
    }
  } catch (error) {
    console.error('获取赛程数据失败:', error)
    ElMessage.error('获取赛程数据失败')
  }
}

const fetchEventDetail = async (eventId) => {
  try {
    const response = await getScheduleById(eventId)
    if (response.code === 200) {
      selectedEvent.value = response.data
      eventDetailVisible.value = true
    } else {
      ElMessage.error(response.message || '获取赛程详情失败')
    }
  } catch (error) {
    console.error('获取赛程详情失败:', error)
    ElMessage.error('获取赛程详情失败')
  }
}

// 事件处理方法
const previousMonth = () => {
  if (currentMonth.value === 1) {
    currentMonth.value = 12
    currentYear.value--
  } else {
    currentMonth.value--
  }
}

const nextMonth = () => {
  if (currentMonth.value === 12) {
    currentMonth.value = 1
    currentYear.value++
  } else {
    currentMonth.value++
  }
}

const goToToday = () => {
  const today = new Date()
  currentYear.value = today.getFullYear()
  currentMonth.value = today.getMonth() + 1
}

const refreshCalendar = () => {
  fetchCalendarEvents()
}

const handleDateClick = (date) => {
  if (date.events.length > 0) {
    handleShowMoreEvents(date)
  }
}

const handleEventClick = (event) => {
  fetchEventDetail(event.id)
}

const handleShowMoreEvents = (date) => {
  selectedDateEvents.value = date.events.sort((a, b) => new Date(a.startTime) - new Date(b.startTime))
  moreEventsVisible.value = true
}

const handleClose = () => {
  dialogVisible.value = false
  emit('schedule-updated')
}

// 监听月份变化
watch([currentYear, currentMonth], () => {
  fetchCalendarEvents()
})

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    fetchCalendarEvents()
  }
})

// 生命周期
onMounted(() => {
  if (dialogVisible.value) {
    fetchCalendarEvents()
  }
})
</script>

<style scoped>
.calendar-container {
  min-height: 600px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.current-month {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  min-width: 120px;
  text-align: center;
}

.header-right {
  display: flex;
  gap: 10px;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background: #e4e7ed;
  margin-bottom: 1px;
}

.weekday {
  background: #f5f7fa;
  padding: 10px;
  text-align: center;
  font-weight: bold;
  color: #606266;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-auto-rows: minmax(100px, auto);
  gap: 1px;
  background: #e4e7ed;
}

.calendar-day {
  background: white;
  padding: 8px;
  min-height: 100px;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
}

.calendar-day:hover {
  background: #f5f7fa;
}

.calendar-day.other-month {
  background: #fafafa;
  color: #c0c4cc;
}

.calendar-day.today {
  background: #ecf5ff;
}

.calendar-day.has-events {
  background: #f9f9f9;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.day-number {
  font-weight: bold;
  color: #303133;
}

.today-label {
  background: #409eff;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
}

.events-container {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.event-item {
  background: #f0f9ff;
  border-left: 3px solid #409eff;
  padding: 4px 6px;
  border-radius: 3px;
  font-size: 11px;
  line-height: 1.3;
  cursor: pointer;
  transition: all 0.2s;
  overflow: hidden;
}

.event-item:hover {
  background: #e1f3ff;
  transform: translateX(2px);
}

.event-time {
  font-weight: bold;
  color: #409eff;
  margin-bottom: 1px;
}

.event-title {
  color: #303133;
  margin-bottom: 1px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.event-venue {
  color: #909399;
  font-size: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.event-pending {
  border-left-color: #909399;
  background: #f4f4f5;
}

.event-pending .event-time {
  color: #909399;
}

.event-progress {
  border-left-color: #e6a23c;
  background: #fdf6ec;
}

.event-progress .event-time {
  color: #e6a23c;
}

.event-completed {
  border-left-color: #67c23a;
  background: #f0f9ff;
}

.event-completed .event-time {
  color: #67c23a;
}

.event-postponed {
  border-left-color: #f56c6c;
  background: #fef0f0;
}

.event-postponed .event-time {
  color: #f56c6c;
}

.event-cancelled {
  border-left-color: #c0c4cc;
  background: #f5f7fa;
  opacity: 0.7;
}

.event-cancelled .event-time {
  color: #c0c4cc;
}

.more-events {
  background: #e1f3ff;
  color: #409eff;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
  text-align: center;
  cursor: pointer;
  margin-top: 2px;
}

.more-events:hover {
  background: #409eff;
  color: white;
}

.event-detail {
  padding: 20px 0;
}

.events-list {
  max-height: 400px;
  overflow-y: auto;
}

.event-card {
  background: #f9f9f9;
  border-left: 4px solid #409eff;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
}

.event-card:hover {
  background: #f0f9ff;
  transform: translateX(5px);
}

.event-card-time {
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.event-card-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.event-card-venue {
  color: #606266;
  margin-bottom: 8px;
}

.event-card-status {
  text-align: right;
}

.no-events {
  text-align: center;
  color: #909399;
  padding: 40px 0;
  font-size: 16px;
}

.dialog-footer {
  text-align: right;
}
</style>